package nl.hanze.designpatterns.mvc.controller;

import java.awt.event.ActionEvent;

import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JPasswordField;
import javax.swing.JTextField;

import nl.hanze.designpatterns.DAO.LoginCredentialDAO;
import nl.hanze.designpatterns.DAO.impl.db.LoginCredentialsDaoImpl;
import nl.hanze.designpatterns.DAOFactory.DAOFactory;
import nl.hanze.designpatterns.domain.LoginCredential;
import nl.hanze.designpatterns.mvc.application.Application;
import nl.hanze.designpatterns.mvc.gui.DashboardGUI;
import nl.hanze.designpatterns.mvc.model.LoginModel;
import nl.hanze.designpatterns.mvc.view.LoginFormView;

public class LoginController extends Controller<LoginModel> {

	private DAOFactory daoFactory;
	
	public LoginController(LoginModel model) {
		super(model);
		
	}
	
	private void setDAOFactory(DAOFactory factory){
		this.daoFactory = factory;
	}
	
	public void Login(String username, String password){
		System.out.println("Trying to login as:" + username);
		LoginCredential cred = new LoginCredential(username, password);
		if(daoFactory != null){
			LoginCredentialDAO credDAO = this.daoFactory.getLoginCredentialDAO();
			if(credDAO.isValid(cred)){
				System.out.println("login succesful!");
				System.out.println("Starting dashboard...");
				Application.setCurrentUser(cred);
				Application.closeLoginGUI();
				Application.startDashboardGUI(cred);
			}else
				System.out.println("login failed!");
		}else{
			System.out.println("[ERR] No factory selected!");
		}
	}
	
	@Override
	public void actionPerformed(ActionEvent e) {
		switch (e.getActionCommand()) {
		case "login":
			JButton button = (JButton)e.getSource();
			String username = ((JTextField) button.getClientProperty("username")).getText();
			String password = new String(((JPasswordField) button.getClientProperty("password")).getPassword());
			this.Login(username, password);
			break;
		case "select_factory":
			JComboBox<DAOFactory> box = (JComboBox<DAOFactory>)e.getSource();
			this.setDAOFactory((DAOFactory) box.getSelectedItem());
			System.out.println("Factory Selected!");
			break;
		default:
			System.out.println("Unhandled Event");
			break;
		}
		super.actionPerformed(e);
		
	}

}
